<template>
  <div class="permission-container">
    <div class="app-container">
      <el-card>
        <div style="text-align: right;margin-bottom: 20px;">
          <el-button type="primary" size="small" @click="showDialog({ type: 1, pid: '0' })">添加权限</el-button>
        </div>
        <!-- el-table 想要渲染成树形结构的表格，需要做两件事： -->
        <!-- 1. 表格渲染的数据，需要是带有 children 的树形结构数据 -->
        <!-- 2. 需要在 el-table 上指定一个 row-key，row-key 的值需要是数据中的唯一标识（一般情况下使用id） -->
        <el-table
          :data="list"
          style="width: 100%"
          border
          row-key="id">
          <el-table-column
            prop="name"
            label="名称">
          </el-table-column>
          <el-table-column
            prop="code"
            label="标识">
          </el-table-column>
          <el-table-column
            prop="description"
            label="描述">
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" @click="showDialog({ type: 2, pid: row.id })">添加</el-button>
              <el-button type="text" @click="showDialogEdit(row.id)">编辑</el-button>
              <el-button type="text" @click="deletePermission(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <permission-dialog 
      ref="permissionDialogRef"
      :visible="visible"
      @close-dialog="closeDialog"
      :type="type"
      :pid="pid"
      @fetch-permission-list="fetchPermissionList">
    </permission-dialog>
  </div>
</template>

<script>
import { getPermissionList, deletePermission } from '@/api/permission'
import { recurTransTree } from '@/utils/transTree'
import PermissionDialog from './components/permission-dialog.vue'

export default {
  components: {
    PermissionDialog
  },
  data() {
    return {
      list: [],
      visible: false,
      type: 1,
      pid: ''
    }
  },
  created() {
    this.fetchPermissionList()
  },
  methods: {
    // 获取权限点列表数据
    async fetchPermissionList() {
      const res = await getPermissionList()
      this.list = recurTransTree(res.data, '0')
    },
    // 显示弹窗
    showDialog({ type, pid }) {
      this.visible = true
      this.type = type
      this.pid = pid
    },
    // 关闭弹窗
    closeDialog() {
      this.visible = false
    },
    // 编辑显示弹窗
    showDialogEdit(id) {
      this.visible = true
      // 调用子组件获取权限点详情的方法
      this.$refs.permissionDialogRef.fetchPermissionDetail(id)
    },
    // 删除权限点
    deletePermission(id) {
      // 询问用户
      this.$confirm('此操作将永久删除该权限点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发起请求
        await deletePermission(id)
        // 提示用户
        this.$message.success('删除权限点成功')
        // 刷新列表
        this.fetchPermissionList()
      })
    }
  }
}
</script>